package com.zzq.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzq.domain.entity.SmilePhotographer;
import com.zzq.enumerate.AuditEnum;
import com.zzq.security.PhotographerSecurityDTO;
import com.zzq.security.ex.AuditAuthenticationException;
import com.zzq.security.ex.NoUserAuthenticationException;
import com.zzq.service.SmilePhotographerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    SmilePhotographerService smilePhotographerService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<SmilePhotographer> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SmilePhotographer::getPhotographerPhone,username);
        SmilePhotographer user = smilePhotographerService.getOne(wrapper);
        //如果查询不到数据就通过抛出异常来给出提示
        if(Objects.isNull(user)){
            throw new NoUserAuthenticationException("用户名不存在");
        }
        String name = AuditEnum.AUDITED.getName();
        if (!user.getAudit().equals(AuditEnum.AUDITED.getName())){
            throw new AuditAuthenticationException("用户未审核");
        }
        //TODO 根据用户查询权限信息 添加到LoginUser中

        //封装成UserDetails对象返回
        return new PhotographerSecurityDTO(user);
    }
}
